﻿#include "edit.h"
#include "ui_edit.h"
#include<QFile>
#include<QDebug>
#include<QtSql/QSqlDatabase>
#include<QtSql/QSqlQuery>
#include<QMessageBox>
edit::edit(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::edit)
{
    ui->setupUi(this);
    QFile file("../edit.css");
    if(file.open(QFile::ReadOnly)){
        QString str=file.readAll();
        setStyleSheet(str);
    }else{
        qDebug()<<"open edit.css fail";
    }
}

edit::~edit()
{
    delete ui;
}

void edit::clearContent()
{
    this->ui->idEdit->clear();
    this->ui->nameEdit->clear();
    this->ui->id->clear();
    this->ui->man->setChecked(true);
    this->ui->dept->setCurrentIndex(0);
    this->ui->fun->clear();
    this->ui->ageEdit->clear();
}

void edit::on_cancelBtn_clicked()
{
    this->close();
    clearContent();
}

void edit::on_okBtn_clicked()
{
    if(!this->db.connectMysql()){
        QMessageBox::critical(this,"改","数据库连接失败!","确定");
        return;
    }
    QSqlQuery query(QString("select* from student where id=%1").arg(this->ui->idEdit->text()));
    if(query.size()<1){
        QMessageBox::critical(this,"改","暂无此学生!","确定");
        return;
    }
    query.next();
    this->ui->nameEdit->setText(query.value("name").toString());
    this->ui->id->setText(query.value("id").toString());
    if(query.value("sex").toString()=="男"){
        this->ui->man->setChecked(true);
    }else{
        this->ui->woman->setChecked(true);
    }
    this->ui->ageEdit->setText(query.value("age").toString());
    this->ui->dept->setCurrentText(query.value("dept").toString());
    this->ui->fun->setText(query.value("fun").toString());
}

void edit::on_editBtn_clicked()
{
    QSqlQuery query(QString("update student set name='%1',sex='%2',age=%3,dept='%4',fun='%5' "
                            "where id=%6").arg(this->ui->nameEdit->text()).arg(this->ui->sexGroup->checkedButton()->text())
                    .arg(this->ui->ageEdit->text().toInt()).arg(this->ui->dept->currentText())
                    .arg(this->ui->fun->text()).arg(this->ui->id->text().toInt()));
    if(query.numRowsAffected()>0){
        QMessageBox::information(this,"改","修改成功!","确定");
    }else{
        QMessageBox::critical(this,"改","信息错误,修改失败!","确定");
    }
}
